% create (EEGLAB) STUDY using all subjects
% ----------------------------------------
subjectNames = { 'c1'  'c2'  'c3'  'c4'  'c5'  'c6'  'c7'  'c8' ...
                 'nd1' 'nd2' 'nd3' 'nd4' 'nd5' 'nd6' 'nd7' 'nd8' };

eeglab;
commands = {};
for index = 1:length(subjectNames);
    filename = fullfile(subjectNames{index}, [ subjectNames{index} '_preprocessed.set' ]);
    commands{end+1} = { 'index' index 'load' filename };
end;
STUDY = [];
ALLEEG = [];
[STUDY ALLEEG] = std_editset( STUDY, ALLEEG,  'commands', commands);
EEG = ALLEEG;
CURRENTSTUDY = 1;
CURRENTSET = [1:length(ALLEEG)];
eeglab redraw

% build trialinfo for STUDY
% -------------------------
for dat = 1:length(ALLEEG)
    STUDY.datasetinfo(dat).group   = fastif(subjectNames{dat}(1) == 'c', 'control', 'nondual');
    STUDY.datasetinfo(dat).subject = subjectNames{dat};
    for e = 1:length(ALLEEG(dat).epoch)
        [tmp tle] = min(abs([ ALLEEG(dat).epoch(e).eventlatency{:} ]));
        STUDY.datasetinfo(dat).trialinfo(e).stimulusType = num2str(ALLEEG(dat).epoch(e).eventtype{tle});
        STUDY.datasetinfo(dat).trialinfo(e).presentation = ALLEEG(dat).epoch(e).eventpresentation{tle};
        STUDY.datasetinfo(dat).trialinfo(e).session      = num2str(ALLEEG(dat).epoch(e).eventsession{tle});
        STUDY.datasetinfo(dat).trialinfo(e).prevevent    = num2str(ALLEEG(dat).epoch(e).eventprevevent{tle});
    end;
end;

save -mat nondual16subjects.study STUDY
